<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="user-level-badge">
        <div class="level-circle">
          <div class="level-inner">
            <span class="level-number">{{ getLevel() }}</span>
            <span class="level-text">级</span>
          </div>
          <svg class="level-progress" viewBox="0 0 36 36">
            <defs>
              <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" style="stop-color: #409eff" />
                <stop offset="100%" style="stop-color: #66b1ff" />
              </linearGradient>
            </defs>
            <path
              d="M18 2.0845
                a 15.9155 15.9155 0 0 1 0 31.831
                a 15.9155 15.9155 0 0 1 0 -31.831"
              fill="none"
              stroke="#e6e6e6"
              stroke-width="2.8"
              stroke-linecap="round"
            />
            <path
              d="M18 2.0845
                a 15.9155 15.9155 0 0 1 0 31.831
                a 15.9155 15.9155 0 0 1 0 -31.831"
              fill="none"
              stroke="url(#gradient)"
              stroke-width="2.8"
              stroke-linecap="round"
              :stroke-dasharray="`${getLevelProgress()}, 100`"
            />
          </svg>
        </div>
        <div class="achievement-badge" :class="getAchievementClass()">
          {{ getAchievementTitle() }}
        </div>
      </div>
    </div>

    <div class="profile-content">
      <div class="profile-info">
        <div class="profile-info-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="editMode = !editMode">
            {{ editMode ? '取消编辑' : '编辑资料' }}
          </el-button>
        </div>

        <el-form 
          :model="editMode ? editForm : userInfo" 
          label-width="100px"
          class="profile-form"
        >
          <div class="info-field">
            <div class="info-field-label">用户名</div>
            <div class="info-field-value" v-if="!editMode">{{ userInfo.username }}</div>
            <el-input v-else v-model="editForm.username" disabled />
          </div>

          <div class="info-field">
            <div class="info-field-label">邮箱</div>
            <div class="info-field-value" v-if="!editMode">{{ userInfo.email }}</div>
            <el-input v-else v-model="editForm.email" disabled />
          </div>

          <div class="info-field">
            <div class="info-field-label">昵称</div>
            <div class="info-field-value" v-if="!editMode">{{ userInfo.nick_name || '未设置' }}</div>
            <el-input v-else v-model="editForm.nick_name" placeholder="设置一个好听的昵称吧" />
          </div>

          <div class="info-field full-width">
            <div class="info-field-label">头像</div>
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>

          <div class="info-field">
            <div class="info-field-label">注册时间</div>
            <div class="info-field-value">{{ formatDate(userInfo.created_time) }}</div>
          </div>

          <div class="info-field">
            <div class="info-field-label">最后登录</div>
            <div class="info-field-value">{{ formatDate(userInfo.last_login) }}</div>
          </div>

          <div class="statistics full-width">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="statistic-header">解决的题目</div>
                  <div class="statistic-value">{{ userInfo.solved_problems || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="statistic-header">提交次数</div>
                  <div class="statistic-value">{{ userInfo.total_submissions || 0 }}</div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div class="statistic-header">通过率</div>
                  <div class="statistic-value">
                    {{ calculateAcceptanceRate(userInfo) }}%
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <div v-if="editMode" class="full-width" style="text-align: center; margin-top: 20px;">
            <el-button type="primary" @click="handleUpdate">保存修改</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { storeToRefs } from 'pinia'
import authApi from '../api/auth'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const editMode = ref(false)
const editForm = ref({
  username: '',
  email: '',
  nick_name: '',
  avatar: '',
})

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '暂无数据'
  return new Date(date).toLocaleString()
}

// 计算通过率
const calculateAcceptanceRate = (user: any) => {
  if (!user.total_submissions) return 0
  return Math.round((user.accepted_submissions / user.total_submissions) * 100)
}

// 获取用户信息
const fetchUserInfo = async () => {
  await userStore.fetchUserInfo()
  editForm.value = {
    username: userInfo.value.username,
    email: userInfo.value.email || '',
    nick_name: userInfo.value.nick_name || '',
    avatar: userInfo.value.avatar || '',
  }
}

// 更新用户信息
const handleUpdate = async () => {
  try {
    const response = await authApi.updateUserInfo({
      email: editForm.value.email,
      nick_name: editForm.value.nick_name,
    })

    if (response.code === 200) {
      userInfo.value = {
        ...userInfo.value,
        ...response.data
      }
      editMode.value = false
      ElMessage.success('更新成功')
    }
  } catch (error) {
    console.error('更新失败:', error)
  }
}

const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    userInfo.value.avatar = response.data.url
    editForm.value.avatar = response.data.url
  }
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const getLevelProgress = () => {
  const solvedProblems = userInfo.value.solved_problems || 0
  const currentLevel = Math.floor(solvedProblems / 10) + 1
  const currentLevelProblems = solvedProblems % 10
  return (currentLevelProblems / 10) * 100
}

const getAchievementClass = () => {
  const solvedProblems = userInfo.value.solved_problems || 0
  const level = Math.floor(solvedProblems / 10) + 1
  if (level >= 10) return 'master'
  if (level >= 5) return 'expert'
  return 'beginner'
}

const getAchievementTitle = () => {
  const solvedProblems = userInfo.value.solved_problems || 0
  const level = Math.floor(solvedProblems / 10) + 1
  if (level >= 10) return '大师'
  if (level >= 5) return '专家'
  return '新手'
}

const getLevel = () => {
  const solvedProblems = userInfo.value.solved_problems || 0
  return Math.floor(solvedProblems / 10) + 1
}

onMounted(() => {
  fetchUserInfo()
})
</script>

